package com.android.datn.activities.offline;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.NameValuePair;

import com.android.datn.MyApplication;
import com.android.datn.R;
import com.android.datn.activities.ADetailMusic;
import com.android.datn.activities.ATop;
import com.android.datn.activities.BaseActivity;
import com.android.datn.activities.GActivityHome;
import com.android.datn.adapter.TracksAdapter;
import com.android.datn.daos.TrackDAO;
import com.android.datn.helper.DBBinding;
import com.android.datn.objects.Album;
import com.android.datn.objects.Artist;
import com.android.datn.objects.Track;
import com.android.datn.repositories.MusicRepository;
import com.android.datn.services.AudioPlayer;
import com.android.datn.utils.CommonUtil;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("NewApi")
public class ASongOfArtist extends BaseActivity implements OnItemClickListener,
		OnClickListener {
	private ArrayList<Track> mArrayTrackItems;
	private TracksAdapter mAdapter;
	private ListView mLvTracks;
	private ProgressDialog mProgressDialog;
	private Artist mArtist;
	private ServiceConnection serviceConnection = new AudioPlayerServiceConnection();
	private AudioPlayer audioPlayer;
	private Intent audioPlayerIntent;
	private Timer waitForAudioPlayertimer = new Timer();
	private Handler handler = new Handler();
	private LinearLayout mLayoutTrack, mLayoutLoading;
	private TextView mTvTrackName, mTvTrackArtist, mTvPleaseChooseSing;
	private ImageView mImgFavorite, mImgPlayPause;
	private Track mTrackCurrent = null;
	private FrameLayout mLayoutDetail;
	private MusicRepository mMusicRespository;
	private BroadcastReceiver audioPlayerBroadcastReceiver = new AudioPlayerBroadCastReceiver();
	private TrackDAO mTrackDAO;
	private boolean mIsTrackFirst = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_song_of_artist);
		init();
	}

	public void init() {
		mTrackDAO = TrackDAO.getInstance();
		mArtist = (Artist) getIntent().getBundleExtra(DBBinding.BUNDLEARTIST)
				.getSerializable(DBBinding.ARTIST);
		mLvTracks = (ListView) findViewById(R.id.lv_item);
		mLayoutLoading = (LinearLayout) findViewById(R.id.layout_loading);
		mLayoutTrack = (LinearLayout) findViewById(R.id.layout_track);
		mTvTrackName = (TextView) findViewById(R.id.txt_name_track);
		mTvTrackArtist = (TextView) findViewById(R.id.txt_artist);
		mImgFavorite = (ImageView) findViewById(R.id.img_favorite);
		mImgPlayPause = (ImageView) findViewById(R.id.img_play_pause);
		mTvPleaseChooseSing = (TextView) findViewById(R.id.txt_please_choose);
		mLayoutDetail = (FrameLayout) findViewById(R.id.layout_detail);
		mLayoutDetail.setOnClickListener(this);
		mImgFavorite.setOnClickListener(this);
		mImgPlayPause.setOnClickListener(this);
		mArrayTrackItems = new ArrayList<Track>();
		/*mAdapter = new TracksAdapter(this, R.layout.view_item_track,
				mArrayTrackItems);*/
		mAdapter = new TracksAdapter(this, R.layout.view_item_track,
				mArrayTrackItems) {
			
			@Override
			public void processVote(int position) {
				// TODO Auto-generated method stub
				
			}
		};
		mLvTracks.setAdapter(mAdapter);
		mLvTracks.setOnItemClickListener(this);
		mProgressDialog = new ProgressDialog(getParent().getParent());
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mProgressDialog.setMessage("Please wait...");
		mProgressDialog.setCancelable(false);
		mMusicRespository = new MusicRepository();
		TrackAsync ws = new TrackAsync();
		ws.execute();
		// bind to service
		audioPlayerIntent = new Intent(getParent().getParent(),
				AudioPlayer.class);
		getParent().getParent().bindService(audioPlayerIntent,
				serviceConnection, Context.BIND_AUTO_CREATE);
		audioPlayerBroadcastReceiver = new AudioPlayerBroadCastReceiver();
		IntentFilter filter = new IntentFilter(DBBinding.SERVICE_SONG_OF_ARTIST);
		registerReceiver(audioPlayerBroadcastReceiver, filter);
		updateTrack();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	public void notification(String message, String title) {
		CommonUtil.dialogNotify(getParent().getParent(), message, title);
	}

	public class TrackAsync extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressDialog.show();
		}

		@Override
		protected void onPostExecute(Void result) {
			mProgressDialog.dismiss();
			mAdapter.notifyDataSetChanged();
		}

		@Override
		protected Void doInBackground(Void... params) {
			for (int i = 0; i < mMusicRespository.findTracksByArtist(
					ASongOfArtist.this, mArtist.getId()).size(); i++) {
				mArrayTrackItems.add(mMusicRespository.findTracksByArtist(
						ASongOfArtist.this, mArtist.getId()).get(i));
			}
			return null;
		}
	}

	@Override
	public void onBackPressed() {
		GActivityOffline.group.back();
	}

	private final class AudioPlayerServiceConnection implements
			ServiceConnection {
		public void onServiceConnected(ComponentName className, IBinder baBinder) {
			audioPlayer = ((AudioPlayer.AudioPlayerBinder) baBinder)
					.getService();
			if (audioPlayer.isPlaying()) {
				mTvPleaseChooseSing.setVisibility(View.GONE);
			} else {
				mTvPleaseChooseSing.setVisibility(View.VISIBLE);
			}
			startService(audioPlayerIntent);
		}

		public void onServiceDisconnected(ComponentName className) {
			audioPlayer = null;
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// audioPlayer.pause();
		mTvPleaseChooseSing.setVisibility(View.GONE);
		mLayoutLoading.setVisibility(View.VISIBLE);
		mLayoutTrack.setVisibility(View.GONE);
		mImgPlayPause.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.ic_pause));
		MyApplication.ArrayTrack.clear();
		for (int i = 0; i < mArrayTrackItems.size(); i++) {
			MyApplication.ArrayTrack.add(mArrayTrackItems.get(i));
		}
		Intent intent = new Intent(DBBinding.INTENT_PLAY_ID);
		intent.putExtra("id", arg2);
		this.sendBroadcast(intent);
	}

	public void updateTrack() {
		waitForAudioPlayertimer.scheduleAtFixedRate(new TimerTask() {
			public void run() {
				if (audioPlayer != null) {
					handler.post(new Runnable() {
						public void run() {
							updateCurrentTrack();
						}
					});
				}
			}
		}, 10, 170);

	}

	public void updateCurrentTrack() {
		mTrackCurrent = audioPlayer.getCurrentTrack();
		if (!mIsTrackFirst & mTrackCurrent != null) {
			mIsTrackFirst = true;
			if (mTrackDAO.getSizeByTitleAndArtist(mTrackCurrent,DBBinding.DB_FAVORITE) > 0) {
				mImgFavorite
						.setBackgroundResource(R.drawable.ic_favorites_active);
			} else {
				mImgFavorite
						.setBackgroundResource(R.drawable.ic_favorite_default);
			}
		}
		if (mTrackCurrent == null) {
		} else {
			runOnUiThread(new Runnable() {
				@SuppressWarnings("deprecation")
				public void run() {
					mLayoutLoading.setVisibility(View.GONE);
					mTvPleaseChooseSing.setVisibility(View.GONE);
					mTvTrackName.setText(mTrackCurrent.getTitle());
					mTvTrackArtist.setText(mTrackCurrent.getArtist());
					if (mTrackCurrent.isPrepared()) {
						mLayoutLoading.setVisibility(View.GONE);
						mLayoutTrack.setVisibility(View.VISIBLE);

					} else {
						mLayoutTrack.setVisibility(View.GONE);
						mLayoutLoading.setVisibility(View.VISIBLE);
					}
					if (audioPlayer.isPlaying()) {
						mImgPlayPause.setBackgroundDrawable(getResources()
								.getDrawable(R.drawable.ic_pause));
					} else {
						mImgPlayPause.setBackgroundDrawable(getResources()
								.getDrawable(R.drawable.ic_play));
					}
				}
			});
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_play_pause:
			if (mTrackCurrent != null) {
				if (mTrackCurrent.isPrepared()) {
					if (audioPlayer.isPlaying()) {
						mImgPlayPause.setBackgroundDrawable(getResources()
								.getDrawable(R.drawable.ic_play));
						audioPlayer.pause();
					} else {
						mImgPlayPause.setBackgroundDrawable(getResources()
								.getDrawable(R.drawable.ic_pause));
						audioPlayer.play();
					}
				}
			}
			break;
		case R.id.layout_detail:
			Intent intent = new Intent(getParent().getParent(),
					ADetailMusic.class);
			startActivity(intent);
			break;
		case R.id.img_favorite:
			if (mTrackDAO.getSizeByTitleAndArtist(mTrackCurrent,DBBinding.DB_FAVORITE) > 0) {
				mTrackDAO.deleteFavorite(mTrackCurrent, DBBinding.DB_FAVORITE);

				Toast.makeText(getBaseContext(),
						"This song is deleted your favorite",
						Toast.LENGTH_SHORT).show();
				mImgFavorite
						.setBackgroundResource(R.drawable.ic_favorite_default);
			} else {
				mTrackDAO.addTrack(mTrackCurrent, DBBinding.DB_FAVORITE);
				Toast.makeText(getBaseContext(),
						"This song added your favorite", Toast.LENGTH_SHORT)
						.show();
				mImgFavorite
						.setBackgroundResource(R.drawable.ic_favorites_active);
			}
			break;
		default:
			break;
		}
	}

	private class AudioPlayerBroadCastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (DBBinding.SERVICE_SONG_OF_ARTIST.equals(intent.getAction())) {
				mIsTrackFirst = true;
				if (mTrackCurrent != null) {
					if (mTrackDAO.getSizeByTitleAndArtist(mTrackCurrent,DBBinding.DB_FAVORITE) > 0) {
						mImgFavorite
								.setBackgroundResource(R.drawable.ic_favorites_active);
					} else {
						mImgFavorite
								.setBackgroundResource(R.drawable.ic_favorite_default);
					}
				}
				// mAdapter.notifyDataSetChanged();
			}
		}
	}
}
